<?php

namespace App\Http\Middleware;

use App\Model\System\Token;
use Closure;
use App\Model\System\AuthUserRole;
use App\Model\System\AuthPermission;
use App\Model\System\AuthRolePermission;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authority
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        # 获取用户id
        $user = Token::user();
        $userid = $user->userid;
        # 获取接口模块
        $api = explode('/', $request->getRequestUri())[2];
        # 获取权限列表
        $permissions = AuthPermission::getPermissionsByUserID($userid);

        # 检查权限
        foreach ($permissions as $permission){
            if(empty($permission->modules)) {
                continue;
            }
            $modules = explode(',', $permission->modules);
            foreach ($modules as $mod){
                if(strstr($api, $mod)!==false){
                    # 有权限
                    return $next($request);
                }
            }
        }
        # 没有权限
        return response('Not Allowed.', 405);
    }
}
